<template>
    <view class="favorites-page">
        <NavBar @back="goBack"></NavBar>
        <!-- 自定义导航栏 -->
        <!-- 收藏列表 -->
        <scroll-view class="content" scroll-y @scrolltolower="loadMore">
            <!-- 收藏统计 -->
            <view class="favorites-info" v-if="!loading && questions.length > 0">
                <text class="result-count">
                    共收藏 {{ total }} 个题目
                </text>
            </view>

            <!-- 题目列表 -->
            <view class="question-list">
                <view class="question-item" v-for="item in questions" :key="item.id" @click="goToDetail(item)">
                    <!-- VIP角标 -->
                    <view class="vip-badge" v-if="item.requirePremium"></view>
                    <view class="question-header">
                        <text class="question-title">{{ item.title }}</text>
                        <view class="question-meta">
                            <view class="difficulty-badge" :class="`difficulty-${item.difficulty}`">
                                {{ getDifficultyText(item.difficulty) }}
                            </view>
                        </view>
                    </view>
                    <view class="question-stats">
                        <text class="publish-date">{{ item.publishDate }}</text>
                        <view class="question-stats-right">
                            <view class="stat-item">
                                <SvgIcon name="view" :size="16" />
                                <text class="stat-text">{{ item.viewCount || 0 }}</text>
                            </view>
                            <view class="stat-item" :class="{ active: item.isLiked }">
                                <SvgIcon :name="item.isLiked ? 'like2' : 'like'" :size="16" />
                                <text class="stat-text">{{ item.likes }}</text>
                            </view>
                            <view class="stat-item" :class="{ active: item.isFavorited }">
                                <SvgIcon :name="item.isFavorited ? 'save2' : 'save'" :size="16" />
                                <text class="stat-text">{{ item.stars }}</text>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 加载更多 -->
                <view class="load-more" v-if="loading">
                    <text class="load-more-text">加载中...</text>
                </view>

                <!-- 没有更多数据 -->
                <view class="no-more" v-if="!loading && questions.length >= total && total > 0">
                    <text class="no-more-text">没有更多了</text>
                </view>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-if="questions.length === 0 && !loading">
                <text class="empty-icon">📚</text>
                <text class="empty-text">暂无收藏</text>
                <text class="empty-desc">快去收藏一些感兴趣的题目吧</text>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useNavBar } from '@/hooks/useNavBar'
import { useUserStore } from '@/stores/user'
import { getInterviewList } from '@/api/interview'
import NavBar from '@/components/NavBar.vue'
import SvgIcon from '@/components/SvgIcon.vue'

// 题目数据类型
interface QuestionItem {
    id: number
    title: string
    question: string
    publishDate: string
    likes: number
    stars: number
    isLiked: boolean
    isFavorited: boolean
    difficulty: number
    categoryId: number
    viewCount: number
    requirePremium: boolean
}

const { navBarHeight, capsuleBottom } = useNavBar()
const userStore = useUserStore()

// 题目数据
const questions = ref<QuestionItem[]>([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

/**
 * 加载收藏列表
 */
const loadFavorites = async (isLoadMore = false) => {
    if (loading.value) return

    loading.value = true
    try {
        const params = {
            categoryId: - 1,
            page: page.value,
            pageSize: pageSize.value
        }

        console.log('请求收藏列表参数:', params)
        const res = await getInterviewList(params)
        console.log('收藏列表响应:', res)

        if (res.code === 200) {
            const newQuestions = res.data.list.map((item: any) => ({
                id: item.id,
                title: item.title || item.question,
                question: item.question,
                publishDate: formatDate(item.createTime),
                likes: item.likeCount,
                stars: item.favoriteCount,
                isLiked: item.isLiked,
                isFavorited: item.isFavorited,
                difficulty: item.difficulty,
                categoryId: item.categoryId,
                viewCount: item.viewCount,
                requirePremium: item.requirePremium || false
            }))

            if (isLoadMore) {
                questions.value = [...questions.value, ...newQuestions]
                console.log('追加收藏数据，当前总数:', questions.value.length)
            } else {
                questions.value = newQuestions
                console.log('替换收藏数据，当前总数:', questions.value.length)
            }

            total.value = res.data.total
            console.log('收藏总数据量:', total.value)
        }
    } catch (error) {
        console.error('加载收藏列表失败:', error)
        uni.showToast({
            title: '加载失败，请重试',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

/**
 * 格式化日期
 */
const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

/**
 * 获取难度文本
 */
const getDifficultyText = (difficulty: number) => {
    const difficultyMap: { [key: number]: string } = {
        1: '简单',
        2: '中等',
        3: '困难',
        4: '专家'
    }
    return difficultyMap[difficulty] || '未知'
}

/**
 * 返回上一页
 */
const goBack = () => {
    uni.navigateBack()
}


/**
 * 跳转到题目详情
 */
const goToDetail = (item: QuestionItem) => {
    console.log('item', item)
    uni.navigateTo({
        url: `/pages/detail/detail?id=${item.id}`
    })
}

/**
 * 加载更多数据
 */
const loadMore = () => {
    console.log('触发加载更多', { loading: loading.value, currentLength: questions.value.length, total: total.value })

    if (loading.value || questions.value.length >= total.value) {
        console.log('跳过加载更多')
        return
    }

    page.value++
    console.log('开始加载第', page.value, '页')
    loadFavorites(true)
}

/**
 * 页面加载时初始化数据
 */
onMounted(() => {
    loadFavorites()
})
</script>

<style lang="scss" scoped>
.favorites-page {
    background-color: #f7f8fa;
    display: flex;
    flex-direction: column;
    height: 100vh;
}

// 导航栏样式
.nav-bar {
    background-color: #fff;
    border-bottom: 1rpx solid #f1f5f9;
}

.nav-content {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    height: 88rpx;
}

.page-title {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;

    .title-text {
        font-size: 36rpx;
        font-weight: 600;
        color: #1f2937;
    }
}


// 内容区域
.content {
    padding: 0;
    flex: 1;
    height: 100%;
}

// 收藏统计
.favorites-info {
    margin-bottom: 24rpx;
    padding: 0 30rpx;

    .result-count {
        font-size: 28rpx;
        color: #6b7280;
    }
}

// 题目列表
.question-list {
    padding: 0 30rpx;

    .question-item {
        background-color: #fff;
        border-radius: 16rpx;
        padding: 32rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
        position: relative;

        &:active {
            background-color: #f9fafb;
        }

        .vip-badge {
            position: absolute;
            top: 0;
            right: 0;
            width: 60rpx;
            height: 60rpx;
            z-index: 10;
            background: #ffd700;
            clip-path: polygon(0 0, 100% 0, 100% 100%);
            border-top-right-radius: 16rpx;

            &::after {
                content: 'VIP';
                position: absolute;
                top: 8rpx;
                right: 4rpx;
                color: #fff;
                font-size: 18rpx;
                font-weight: bold;
                transform: rotate(45deg);
                transform-origin: center;
            }
        }

        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 24rpx;

            .question-title {
                flex: 1;
                font-size: 32rpx;
                font-weight: 500;
                color: #1f2937;
                line-height: 1.5;
                margin-right: 20rpx;
            }

            .question-meta {
                display: flex;
                align-items: center;
                gap: 16rpx;

                .difficulty-badge {
                    padding: 4rpx 12rpx;
                    border-radius: 12rpx;
                    font-size: 20rpx;
                    font-weight: 500;

                    &.difficulty-1 {
                        background-color: #dcfce7;
                        color: #16a34a;
                    }

                    &.difficulty-2 {
                        background-color: #fef3c7;
                        color: #d97706;
                    }

                    &.difficulty-3 {
                        background-color: #fee2e2;
                        color: #dc2626;
                    }

                    &.difficulty-4 {
                        background-color: #f1f5f9;
                        color: #64748b;
                    }
                }

                .publish-date {
                    font-size: 24rpx;
                    color: #9ca3af;
                }
            }
        }

        .question-stats {
            display: flex;
            gap: 32rpx;
            justify-content: space-between;

            .question-stats-right {
                display: flex;
                align-items: center;
                gap: 32rpx;
            }

            .stat-item {
                display: flex;
                align-items: center;
                gap: 8rpx;

                .stat-icon {
                    font-size: 24rpx;
                }

                .stat-text {
                    font-size: 24rpx;
                    color: #6b7280;
                }
            }
        }
    }
}

// 空状态
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 0;

    .empty-icon {
        font-size: 120rpx;
        margin-bottom: 32rpx;
    }

    .empty-text {
        font-size: 32rpx;
        color: #6b7280;
        margin-bottom: 16rpx;
    }

    .empty-desc {
        font-size: 28rpx;
        color: #9ca3af;
    }
}

// 加载更多
.load-more,
.no-more {
    text-align: center;
    padding: 40rpx 0;

    .load-more-text,
    .no-more-text {
        font-size: 28rpx;
        color: #9ca3af;
    }
}

// 状态激活样式
.stat-item.active {
    .stat-text {
        color: #ef4444;
    }
}
</style>
